package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";

	protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
                                                 IOException {

		execute(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "hello world from doget()";
        request.setAttribute("message", message);
        RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/helloworld.jsp");
        view.forward(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	res.setCharacterEncoding("UTF-8");
        PrintWriter out = res.getWriter();
        res.setContentType(CONTENT_TYPE);
        System.out.println("TestServlet : Start");
        try {
        	String test = req.getParameter("test");
        	
        	System.out.println("Test = " + test);
        	
        } catch (Exception e) {
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        System.out.println("TestServlet : End");
	}

	private void execute(HttpServletRequest req,
	   HttpServletResponse res) throws ServletException,
	                                   IOException {
		res.setCharacterEncoding("UTF-8");
        PrintWriter out = res.getWriter();
        res.setContentType(CONTENT_TYPE);
        System.out.println("TestServlet : Start");
        try {
        	String test = req.getParameter("test");
        	
        	System.out.println("Test = " + test);
        	
        } catch (Exception e) {
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        System.out.println("TestServlet : End");
	}
}
